package cn.ppool.xmlmapper.builder.parse.model.entry;

import cn.ppool.xmlmapper.builder.MapperBuilder;
import cn.ppool.xmlmapper.builder.annotation.Insert;
import cn.ppool.xmlmapper.builder.parse.model.base.BaseEntryBO;
import cn.ppool.xmlmapper.builder.parse.model.base.BaseFuncBO;
import cn.ppool.xmlmapper.builder.xml.XNode;
import cn.ppool.xmlmapper.builder.xml.XPathParser;
import cn.ppool.xmlmapper.utils.StringUtil;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;

public class InsertBO extends BaseEntryBO {
    public final static String TAG_NAME = "INSERT";


    @Override
    public Insert getFunAnt() {
        return (Insert) super.getFunAnt();
    }

    public InsertBO(MapperBuilder configure, final XNode rootNode, XNode currentNode, final Method method, final String id) {
        super(configure, rootNode, currentNode, method,id);
        super.fun = TAG_NAME;
        Insert insertAnt = method.getAnnotation(Insert.class);
        if (insertAnt != null) {
            super.funAnt = insertAnt;
            if (insertAnt.sql().length > 0) {
                StringBuffer strSql = new StringBuffer()
                        .append("<insert>").append(StringUtil.appendStrList(Arrays.asList(insertAnt.sql()), "\n")).append("</insert>");
                super.originSql = strSql.toString();
                XPathParser pp = new XPathParser(strSql.toString(), false);
                currentNode = pp.evalNode("/insert");
            }
        }else{
            super.originSql = currentNode.getStringBody();
        }
        super.sqlList = super.buildModel(configure, rootNode, currentNode);
    }

    @Override
    public void buildEntityModel() {

    }

    @Override
    public String complieEntity(Map<String, Object> allVar, Map<String, Object> sqlVar, StringBuilder sql) {
        BaseFuncBO lo = null;
        for (BaseFuncBO bo : getSqlList()) {
            sql.append(bo.complieEntity(allVar, sqlVar, sql, lo));
            lo = bo;
        }
        return sql.toString();
    }

}
